//
//  ZiViewController.m
//  JinChengYun
//
//  Created by 金橙云 on 2017/2/28.
//  Copyright © 2017年 金橙云. All rights reserved.
//

#import "ZiViewController.h"

#import "TodoHttpManager.h"
#import "UIImageView+WebCache.h"
static CGRect oldframe;
@interface ZiViewController ()<UITextFieldDelegate>
{
   



}
@end

@implementation ZiViewController

-(void)viewWillAppear:(BOOL)animated
{
    //个人信息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDGetMineGetInfo:) name:TDGetMineGetInfo object:nil];
    
    //修改个人信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDGetSetMineGetInfo:) name:TDGetSetMineGetInfo object:nil];


}

-(void)viewWillDisappear:(BOOL)animated
{
    //移除个人信息
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDGetMineGetInfo object:nil];
    
    //移除个人信息
     [[NSNotificationCenter defaultCenter] removeObserver:self name:TDGetSetMineGetInfo object:nil];

}

//个人信息
-(void)didTDGetMineGetInfo:(NSNotification *)notifi
{
    if (notifi.object != nil)
    {
        int status = [[notifi.object objectForKey:@"status"] intValue];
        if (status == 1)
        {
           
            _zongDic = [notifi.object objectForKey:@"data"];
            
            if ([[_zongDic objectForKey:@"img"] isKindOfClass:[NSString class]])
            {
                
                if ([[_zongDic objectForKey:@"img"] isKindOfClass:[NSString class]])
                {
                    if (![[_zongDic objectForKey:@"img"] isEqualToString:@""] && [_zongDic objectForKey:@"img"] != nil)
                    {
                        [_Img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_zongDic objectForKey:@"img"]]] placeholderImage:[UIImage imageNamed:@"Me_header"]];
                       
                    }
               
                }
          
            }
            
            if(![[_zongDic objectForKey:@"name"] isKindOfClass:[NSNull class]]){
                _nameTF.text = [_zongDic objectForKey:@"name"];

            }
            if(![[_zongDic objectForKey:@"bumen"] isKindOfClass:[NSNull class]]){
                _buMenTF.text = [_zongDic objectForKey:@"bumen"];
                
            }
            if(![[_zongDic objectForKey:@"zhiwei"] isKindOfClass:[NSNull class]]){
                _zhiWeiTF.text = [_zongDic objectForKey:@"zhiwei"];
                
            }
            if(![[_zongDic objectForKey:@"telephone"] isKindOfClass:[NSNull class]]){
                _phoneTF.text = [_zongDic objectForKey:@"telephone"];
                
            }
            if(![[_zongDic objectForKey:@"img"] isKindOfClass:[NSNull class]]){
                _headImg = [_zongDic objectForKey:@"img"];
                
            }

            [[NSNotificationCenter defaultCenter]postNotificationName:@"labelTextNotification" object: _nameTF.text];

        }
 
    }
    
}


//个人信息修改
-(void)didTDGetSetMineGetInfo:(NSNotification *)notifica
{
    if (notifica.object != nil)
    {
        int status = [[notifica.object objectForKey:@"status"] intValue];
        if (status == 1)
        {
            [_manager MakeMyselfAlert:@"上传成功" andIsNeedTitle:YES andShowTime:2.0];
            
            if (localUImage)
            {
                if (imgUrl != nil && ![imgUrl isEqualToString:@""])
                {
                    //清除之前的缓存
                    [[SDImageCache sharedImageCache]removeImageForKey:imgUrl];
                }
                else
                {
                    [[NSUserDefaults standardUserDefaults]setObject:UIImageJPEGRepresentation(localUImage, 0.3) forKey:@"LocalHeadImage"];
                }

            }
       
            
        }
        else
        {
            [_manager MakeMyselfAlert:@"上传失败" andIsNeedTitle:YES andShowTime:2.0];
        }
        
    
        
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人资料";
    self.view.backgroundColor = [UIColor whiteColor];
    NSUserDefaults *userDefa = [NSUserDefaults standardUserDefaults];
    
    NSString *uid= [userDefa objectForKey:@"USER_ID"];
    
    _zongDic = [NSMutableDictionary dictionaryWithCapacity:0];
    //TODO: 个人信息请求OR个人信息修改
    _manager = [TodoHttpManager sharedManager];
   
    [_manager userGetMineInfoGetWithID:uid];
     NSLog(@"---------------%@",uid);
    
    [self SetUpUI];
    
    imgUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"NetHeadImage"];
    if (imgUrl != nil && ![imgUrl isEqualToString:@""])  
    {
        [_Img sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
    }

    //localUImage = nil;
}

-(void)SetUpUI
{
    UILabel *touLab = [[UILabel alloc] init];
    touLab.text = @"头像";
    touLab.font = [UIFont systemFontOfSize:16];
    //touLab.backgroundColor = [UIColor redColor];
    touLab.textColor = [UIColor blackColor];
    [self.view addSubview:touLab];
    [touLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 18));
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(self.view.mas_top).offset(85);
    }];
    
    _Img = [[UIImageView alloc] init];
   // _Img.backgroundColor = [UIColor yellowColor];
    _Img.layer.cornerRadius = 22.5;
    [self.view addSubview:_Img];
    [_Img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(45, 45));
        make.left.equalTo(self.view.mas_left).offset(B_WIDTH/2-20);
        make.top.equalTo(self.view.mas_top).offset(72);
    }];
    
    _imgBtn = [ UIButton buttonWithType:UIButtonTypeCustom];
    _imgBtn.layer.cornerRadius = 22.5;
    _imgBtn.layer.masksToBounds = YES;
    [_imgBtn addTarget:self action:@selector(upLoadBtnClick:) forControlEvents:UIControlEventTouchUpInside];;
    [self.view addSubview:_imgBtn];
    [_imgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(45, 45));
        make.left.equalTo(self.view.mas_left).offset(B_WIDTH/2-20);
        make.top.equalTo(self.view.mas_top).offset(72);

    }];

    UILabel *line1 = [[UILabel alloc] init];
    line1.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(B_WIDTH, 0.5));
        make.top.equalTo(self.view.mas_top).offset(124);
       
    }];
    
    
    //姓名
    UILabel *nameLab = [[UILabel alloc] init];
    nameLab.text = @"姓名";
    nameLab.font = [UIFont systemFontOfSize:16];
    //touLab.backgroundColor = [UIColor redColor];
    nameLab.textColor = [UIColor blackColor];
    [self.view addSubview:nameLab];
    [nameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 18));
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(line1.mas_bottom).offset(15);
    }];
    
    _nameTF = [[UITextField alloc] init];
    _nameTF.borderStyle = UITextBorderStyleRoundedRect;
    _nameTF.delegate = self;
    [self.view addSubview:_nameTF];
    [_nameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 30));
        make.left.equalTo(self.view.mas_left).offset(80);
        make.top.equalTo(line1.mas_bottom).offset(10);
    }];
    
    //密码
    UILabel *line2 = [[UILabel alloc] init];
    line2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(B_WIDTH, 0.5));
        make.top.equalTo(line1.mas_bottom).offset(50);
        
    }];
    
    UILabel *miLab = [[UILabel alloc] init];
    miLab.text = @"密码";
    miLab.font = [UIFont systemFontOfSize:16];
    //touLab.backgroundColor = [UIColor redColor];
    miLab.textColor = [UIColor blackColor];
    [self.view addSubview:miLab];
    [miLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 18));
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(line2.mas_bottom).offset(15);
    }];
    
    _miMaTF = [[UITextField alloc] init];
    _miMaTF.borderStyle = UITextBorderStyleRoundedRect;
    _miMaTF.placeholder = @"无需修改密码请留空";
    _miMaTF.font = [UIFont systemFontOfSize:14];
    _miMaTF.userInteractionEnabled = NO;
    _miMaTF.delegate = self;
    [self.view addSubview:_miMaTF];
    [_miMaTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 30));
        make.left.equalTo(self.view.mas_left).offset(80);
        make.top.equalTo(line2.mas_bottom).offset(10);
    }];

    
    
    //部门
    
    UILabel *line3 = [[UILabel alloc] init];
    line3.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line3];
    [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(B_WIDTH, 0.5));
        make.top.equalTo(line2.mas_bottom).offset(50);
        
    }];
    
    UILabel *buLab = [[UILabel alloc] init];
    buLab.text = @"部门";
    buLab.font = [UIFont systemFontOfSize:16];
    buLab.textColor = [UIColor blackColor];
    [self.view addSubview:buLab];
    [buLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 18));
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(line3.mas_bottom).offset(15);
    }];
    
    _buMenTF = [[UITextField alloc] init];
    _buMenTF.borderStyle = UITextBorderStyleRoundedRect;
   // _buMenTF.placeholder = @"无需修改密码请留空";
    _buMenTF.font = [UIFont systemFontOfSize:14];
    _buMenTF.delegate = self;
      _buMenTF.userInteractionEnabled = NO;
    [self.view addSubview:_buMenTF];
    [_buMenTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 30));
        make.left.equalTo(self.view.mas_left).offset(80);
        make.top.equalTo(line3.mas_bottom).offset(10);
    }];

    
    //职位
    
    UILabel *line4 = [[UILabel alloc] init];
    line4.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line4];
    [line4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(B_WIDTH, 0.5));
        make.top.equalTo(line3.mas_bottom).offset(50);
        
    }];
    
    UILabel *zhiLab = [[UILabel alloc] init];
    zhiLab.text = @"职位";
    zhiLab.font = [UIFont systemFontOfSize:16];
    zhiLab.textColor = [UIColor blackColor];
    [self.view addSubview:zhiLab];
    [zhiLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 18));
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(line4.mas_bottom).offset(15);
    }];
    
    _zhiWeiTF = [[UITextField alloc] init];
    _zhiWeiTF.borderStyle = UITextBorderStyleRoundedRect;
    _zhiWeiTF.font = [UIFont systemFontOfSize:14];
    _zhiWeiTF.delegate = self;
      _zhiWeiTF.userInteractionEnabled = NO;
    [self.view addSubview:_zhiWeiTF];
    [_zhiWeiTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 30));
        make.left.equalTo(self.view.mas_left).offset(80);
        make.top.equalTo(line4.mas_bottom).offset(10);
    }];

    //手机号
    
    UILabel *line5 = [[UILabel alloc] init];
    line5.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line5];
    [line5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(B_WIDTH, 0.5));
        make.top.equalTo(line4.mas_bottom).offset(50);
        
    }];
    
    UILabel *phoneLab = [[UILabel alloc] init];
    phoneLab.text = @"手机号";
    phoneLab.font = [UIFont systemFontOfSize:16];
    phoneLab.textColor = [UIColor blackColor];
    [self.view addSubview:phoneLab];
    [phoneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 18));
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(line5.mas_bottom).offset(15);
    }];
    
    _phoneTF = [[UITextField alloc] init];
    _phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    // _buMenTF.placeholder = @"无需修改密码请留空";
    _phoneTF.font = [UIFont systemFontOfSize:14];
    _phoneTF.delegate = self;
    [self.view addSubview:_phoneTF];
    [_phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 30));
        make.left.equalTo(self.view.mas_left).offset(80);
        make.top.equalTo(line5.mas_bottom).offset(10);
    }];

    UILabel *line6 = [[UILabel alloc] init];
    line6.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line6];
    [line6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(B_WIDTH, 0.5));
        make.top.equalTo(line5.mas_bottom).offset(50);
        
    }];
    
    _cunBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _cunBtn.layer.cornerRadius = 8;
    _cunBtn.backgroundColor = [UIColor orangeColor];
    [_cunBtn setTitle:@"保存" forState:0];
    [_cunBtn addTarget:self action:@selector(baoCunBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_cunBtn setTitleColor:[UIColor whiteColor] forState:0];
    [self.view addSubview:_cunBtn];
    [_cunBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(B_WIDTH-20*2, 45));
        make.top.equalTo(line6.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(20);
    }];
    
    
    
    
 }


-(void)upLoadBtnClick:(UIButton *)btn
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    UIAlertController* alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    
    [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];

    
    [alertC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
                       {
                           [self presentViewController:picker animated:YES completion:nil];
                           picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                           picker.allowsEditing = YES;
                           picker.delegate = self;
                           
                       }]];
    
    [alertC addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                       {
                           [self presentViewController:picker animated:YES completion:nil];
                           picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                           picker.allowsEditing = YES;
                           picker.delegate = self;
                       }]];

    [alertC.view setTintColor:[UIColor colorWithRed:37/255.0 green:85/255.0 blue:100/255.0 alpha:1]];
    
    [self presentViewController:alertC animated:YES completion:nil];
    
    
}
-(void)baoCunBtnClick:(UIButton *)btn
{
    NSUserDefaults *userDefa = [NSUserDefaults standardUserDefaults];
    
    NSString *uid= [userDefa objectForKey:@"USER_ID"];
    
    NSString* img = nil;
    
    if (localUImage)
    {
        img = [ UIImagePNGRepresentation(localUImage) base64Encoding];
    }
    
    NSLog(@"-----头像没有信息吗------%@",_ImageUrl);
    //TODO:个人信息修改
   [_manager userGetMineInfoSetHeadImage:_ImageUrl andName:_nameTF.text andUserID:uid andPwd:_miMaTF.text andPhone:_phoneTF.text];
    
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    /*添加处理选中图像代码*/
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [_Img setImage:image];
    
    localUImage = image;
    
  //  NSData* data_imghead = UIImagePNGRepresentation(localUImage);
    NSData *imageData = UIImageJPEGRepresentation(localUImage, 0.5);
    NSString *string = [NSString stringWithFormat:@"%@",[imageData base64EncodedStringWithOptions:0]];
    //  [dic setObject:string forKey:@"photo"];
    
    _ImageUrl = string;

    if (_ImageUrl == nil || [_ImageUrl isEqualToString:@""])
    {
        //第一次没有图片，则先把本地图片传回上级页面使用，用完即销毁
        
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    /*添加代码，处理选中图像又取消的情况*/
    [picker dismissViewControllerAnimated:YES completion:nil];
}


+(void)showImage:(UIImageView *)avatarImageView
{
    UIImage *image=avatarImageView.image;
    UIWindow *window=[UIApplication sharedApplication].keyWindow;
    UIView *backgroundView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    oldframe=[avatarImageView convertRect:avatarImageView.bounds toView:window];
    backgroundView.backgroundColor=[UIColor blackColor];
    backgroundView.alpha=0;
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:oldframe];
    imageView.image=image;
    imageView.tag=1;
    [backgroundView addSubview:imageView];
    [window addSubview:backgroundView];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
    [backgroundView addGestureRecognizer: tap];
    
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame=CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
        backgroundView.alpha=1;
    } completion:^(BOOL finished) {
        
    }];
}
//缩小图片
+(void)hideImage:(UITapGestureRecognizer*)tap{
    UIView *backgroundView=tap.view;
    UIImageView *imageView=(UIImageView*)[tap.view viewWithTag:1];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame=oldframe;
        backgroundView.alpha=0;
    } completion:^(BOOL finished) {
        [backgroundView removeFromSuperview];
    }];
}

//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//   // textField.borderStyle = UITextBorderStyleRoundedRect;
//    textField.layer.cornerRadius=8.0f;
//    textField.layer.masksToBounds=YES;
//    textField.layer.borderColor=[[UIColor redColor]CGColor];
//    textField.layer.borderWidth= 1.0f;
//    return YES;
//}
//
//-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
//{
//    //textField.layer.cornerRadius=8.0f;
//    //textField.layer.masksToBounds=YES;
//    textField.layer.borderColor=[[UIColor whiteColor]CGColor];
//    textField.layer.borderWidth= 1.0f;
//     textField.borderStyle = UITextBorderStyleRoundedRect;
//    return YES;
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
